<script setup name="File">
import { Splitpanes, Pane } from 'splitpanes'
import { getIcon } from '@/utils/file'
import 'splitpanes/dist/splitpanes.css'
import hljs from 'highlight.js'
import 'highlight.js/styles/default.css'
const ipc = require("electron").ipcRenderer;
const fs = require('fs')

const handleOpen = async () => {
  ipc.send('openDialog');
}

const files = ref([])

ipc.on('openFiles', (event, arg) => {
  console.log(arg);
  const { root, data } = JSON.parse(arg);
  expands.value = [root.path]
  files.value = arrayToTree(data, root.parentPath)
})

function arrayToTree(list, parentPath = null) {
  const arr = []
  list.forEach(item => {
    if (item.parentPath === parentPath) {

      // 找到了匹配的节点
      // 当前节点的id 和 当前节点的子节点的pid是相等的
      const children = arrayToTree(list, item.path)
      // 找到的节点的子节点
      item.children = children

      arr.push(item)
    }
  })
  return arr
}

const content = ref({

})

const expands = ref([])

const handleSelected = (keys, { selected, node }) => {
  if (!selected || node.type == 1) {
    return;
  }
  if (node.name.indexOf('.png') >= 0 ||
    node.name.indexOf('.svg') >= 0 ||
    node.name.indexOf('.gif') >= 0) {
    content.value = {
      type: 'img',
      content: node.path
    }
  } else {
    fs.readFile(node.path, (err, data) => {
      content.value = {
        type: 'text',
        content: data
      };
      hljs.highlightAll();
    });
  }
}
</script>

<template>
  <page-wrapper class="file-content" style="padding: 0">
    <splitpanes class="w-full default-theme file-view">
      <pane class="flex flex-col" size="30" max-size="80">
        <a-button @click="handleOpen" type="outline" class="m-1">打开文件夹</a-button>
        <a-tree :data="files" v-model:expanded-keys="expands" :fieldNames="{
          key: 'path',
          title: 'name',
          children: 'children',
        }" show-line @select="handleSelected">
          <template #switcher-icon="node">
            <icon icon="vscode-icons:default-folder-opened" v-if="node.type == 1" />
            <template v-else>
              <icon :icon="getIcon(node.name)" />
            </template>
          </template>
        </a-tree>
      </pane>
      <pane class="code-view">
        <img :src="content.content" v-if="content.type == 'img'" />
        <div else>
          <pre>
            <code class="language-html">{{ content.content }}</code>
          </pre>
        </div>
      </pane>
    </splitpanes>

  </page-wrapper>
</template>

<style lang="less" scoped>
.file-content {
  .file-view {
    :deep(.splitpanes__pane) {
      background-color: var(--color-neutral-2) !important;
      overflow: hidden;
    }

    :deep(.arco-tree) {
      height: 100%;
      overflow-y: auto;

      &::-webkit-scrollbar {
        display: none;
      }
    }
  }

  .code-view {
    overflow-y: auto;
  }

}
</style>